<template>
  <div class="registerForm">
    <el-form :model="form" :rules="rules" ref="form" label-width="80px">
      <!-- 用户名/手机 -->
      <el-form-item prop="username">
        <el-input v-model="form.username" placeholder="用户名/手机" @focus="clearErrMsg('username')"></el-input>
      </el-form-item>

      <!-- 验证码 -->
      <el-form-item prop="captcha" class="captcha">
        <el-input v-model="form.captcha" placeholder="验证码" @focus="clearErrMsg('captcha')"></el-input>
        <el-button type="info" plain>
          <div @click="sendCaptcha">发送验证码</div>
        </el-button>
      </el-form-item>

      <!-- 昵称 -->
      <el-form-item prop="nickname">
        <el-input v-model="form.nickname" placeholder="昵称" @focus="clearErrMsg('nickname')"></el-input>
      </el-form-item>

      <!-- 密码 -->
      <el-form-item prop="password">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="密码"
          @focus="clearErrMsg('password')"
        ></el-input>
      </el-form-item>

      <!-- 确认密码 -->
      <el-form-item prop="rePassword">
        <el-input
          v-model="form.rePassword"
          type="password"
          placeholder="确认密码"
          @focus="clearErrMsg('rePassword')"
        ></el-input>
      </el-form-item>

      <!-- 注册 -->
      <el-form-item>
        <el-button type="primary" @click="submitRegister">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    const passwordValidator = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    return {
      form: {
        username: "",
        captcha: "",
        nickname: "",
        password: "",
        rePassword: ""
      },

      rules: {
        username: [
          { required: true, message: "请输入用户名/手机", trigger: "blur" },
          { min: 11, max: 11, message: "长度在 11 个字符", trigger: "blur" }
        ],
        captcha: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { min: 6, max: 6, message: "长度在 6 个字符", trigger: "blur" }
        ],
        nickname: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 16, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        rePassword: [
          {
            required: true,
            validator: passwordValidator,
            trigger: "blur"
          }
        ]
      }
    };
  },

  methods: {
    clearErrMsg(prop) {
      this.$refs.form.clearValidate(prop);
    },

    sendCaptcha() {
      if (!this.form.username) {
        this.$message({
          showClose: true,
          message: "请先输入手机号码",
          type: "error"
        });
      } else {
        this.$axios({
          url: "/captchas",
          method: "POST",
          data: {
            tel: this.form.username
          }
        }).then(res => {
          console.log("手机验证码返回结果", res);
          this.$confirm(`您的手机验证码为：${res.data.code}`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          });
        });
      }
    },

    submitRegister() {
      this.$refs.form.validate((isPass, objNotPass) => {
        if (isPass) {
          console.log(this.form);

          const { rePassword, ...data } = this.form;

          this.$axios({
            url: "/accounts/register",
            method: "POST",
            data
          })
            .then(res => {
              console.log("注册的结果返回", res);

              // 调用vuex的actions发送注册异步请求
              // 实现将注册的数据存储到本地
              this.$store.dispatch("user/register", res.data);

              // 如果本地存储中有token值
              // 实现跳转到登录页
              if (res.data.token) {
                // 弹出登录成功
                this.$message.success("注册成功");

                // 假设当前页是登录页才跳转到主页
                if (this.$route.path === "/user/login") {
                  this.$router.push("/");
                }
              }
            })
            .catch(error => {
              console.log("错误结果", error);
            });
        } else {
          console.log(objNotPass);
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.registerForm {
  width: 400px;
  background-color: #fff;
  border-radius: 0 16px 16px 0;
  background-color: rgba(235, 229, 228, 0.5);

  .el-form {
    padding: 30px;

    .el-form-item {
      margin-bottom: 26px;

      &:last-child {
        margin-bottom: 0px !important;
      }

      /deep/ .el-form-item__content {
        margin-left: 0px !important;
      }

      .el-button {
        width: 100%;
      }
    }

    .captcha {
      /deep/ .el-form-item__content {
        display: flex;

        .el-input {
          flex: 1;
        }

        .el-button {
          width: 112px;
        }
      }
    }
  }
}
</style>